<template>
  <view class="work-container">
    <!-- 轮播图 -->
    <uni-swiper-dot class="uni-swiper-dot-box" :info="bannerData" :current="current" field="content">
      <swiper class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
        <swiper-item v-for="(item, index) in bannerData" :key="index">
          <view class="swiper-item" @click="clickBannerItem(item)">
            <image :src="item.image" mode="aspectFill" :draggable="false" class="banner-image" />
          </view>
        </swiper-item>
      </swiper>
    </uni-swiper-dot>

    <!-- 动态模块宫格 -->
    <view v-for="module in workModules" :key="module.name" class="module-section">
      <uni-section :title="module.name" type="line"></uni-section>
      <view class="grid-body">
        <uni-grid :column="gridColumn" :showBorder="false">
          <uni-grid-item 
            v-for="(item, index) in module.children" 
            :key="index"
          >
            <view class="grid-item-box" @click="navigateToModule(item)">
              <uni-icons :type="item.icon" :size="iconSize"></uni-icons>
              <text class="text">{{ item.name }}</text>
            </view>
          </uni-grid-item>
        </uni-grid>
      </view>
    </view>

    <!-- 无权限提示 -->
    <view v-if="workModules.length === 0" class="no-permission">
      <uni-icons type="info" size="60" color="#999"></uni-icons>
      <text class="no-permission-text">暂无可用模块，请联系管理员分配权限</text>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'WorkIndex',
  data() {
    return {
      current: 0,
      swiperDotIndex: 0,
      bannerData: [  {
        image: '/static/images/banner/gzkj_logo.png'
      },{
        image: '/static/images/banner/niaokan1.png'
      },
        {
          image: '/static/images/banner/niaokan2.png'    
        },


        ],
      workModules: [],
      isDev: process && process.env && process.env.NODE_ENV !== 'production'
    }
  },
  computed: {
    ...mapGetters(['roles', 'permissions']),
    // 根据屏幕宽度动态计算宫格列数
    gridColumn() {
      const systemInfo = uni.getSystemInfoSync()
      const screenWidth = systemInfo.screenWidth
      // 手机：4列，小平板：5列，大平板：6列
      if (screenWidth < 600) {
        return 4
      } else if (screenWidth < 900) {
        return 5
      } else {
        return 6
      }
    },
    // 根据屏幕宽度动态计算图标大小
    iconSize() {
      const systemInfo = uni.getSystemInfoSync()
      const screenWidth = systemInfo.screenWidth
      // 手机：30，小平板：36，大平板：42
      if (screenWidth < 600) {
        return 30
      } else if (screenWidth < 900) {
        return 36
      } else {
        return 42
      }
    }
  },
  
  onLoad() {
    this.loadWorkModules()
  },
  
  onShow() {
    // 每次显示时重新加载模块，以防权限变化
    this.loadWorkModules()
  },
  
  methods: {
    // 加载工作台模块
    loadWorkModules() {
      try {
        if (this.isDev) {
          console.log('=== 开始加载工作台模块 ===')
          console.log('用户角色:', this.roles)
          console.log('用户权限:', this.permissions)
          console.log('后端路由数据:', this.$store.getters.backendRouters)
        }
        
        this.workModules = this.generateWorkModules()
        if (this.isDev) {
          console.log('工作台模块加载完成:', this.workModules)
          console.log('模块数量:', this.workModules.length)
        }
        
        // 详细打印每个模块的信息
        if (this.isDev) {
          this.workModules.forEach((module, index) => {
            console.log(`模块 ${index + 1}:`, {
              name: module.name,
              icon: module.icon,
              childrenCount: module.children ? module.children.length : 0,
              children: module.children
            })
            
            if (module.children) {
              module.children.forEach((child, childIndex) => {
                console.log(`  子模块 ${childIndex + 1}:`, {
                  name: child.name,
                  path: child.path,
                  icon: child.icon,
                  component: child.component
                })
              })
            }
          })
        }
        
        // 如果没有模块，尝试使用默认配置
        if (this.workModules.length === 0) {
          if (this.isDev) console.log('尝试使用默认配置...')
          this.workModules = this.getDefaultModules()
        }
        
        if (this.isDev) console.log('=== 工作台模块加载完成 ===')
      } catch (error) {
        console.error('加载工作台模块失败:', error)
        this.workModules = this.getDefaultModules()
      }
    },
    
    // 生成工作台模块
    generateWorkModules() {
        const workModules = []
        
        // 首先添加默认基础模块
        workModules.push(...this.getDefaultModules())
        
        // 如果有后端路由数据，转换并添加（但要避免重复）
        const backendRouters = this.$store.getters.backendRouters || []
        if (backendRouters.length > 0) {
          try {
            const backendModules = this.convertBackendRoutes(backendRouters)
            
            // 过滤掉重复的模块（避免重复显示app模块）
            backendModules.forEach(backendModule => {
              const existingModule = workModules.find(module => module.name === backendModule.name)
              if (!existingModule) {
                workModules.push(backendModule)
              } else {
                if (this.isDev) console.log(`跳过重复模块: ${backendModule.name}`)
              }
            })
            
            if (this.isDev) console.log('后端路由转换成功:', backendModules.length, '个模块')
          } catch (error) {
            if (this.isDev) console.warn('后端路由转换失败:', error)
          }
        }
        
        return workModules
    },
    
    // 转换后端路由数据（处理API返回的数据结构）
    convertBackendRoutes(backendRoutes) {
      const mobileModules = []
      
      backendRoutes.forEach(route => {
        if (route.hidden) return
        
        // 创建模块
        const module = {
          name: route.meta?.title || route.name,
          icon: this.getMobileIcon(route.meta?.icon),
          children: []
        }
        
        // 处理子路由
        if (route.children && Array.isArray(route.children)) {
          route.children.forEach(child => {
            if (child.hidden) return
            
            const mobileRoute = {
              name: child.meta?.title || child.name,
              title: child.meta?.title || child.name,
              icon: this.getMobileIcon(child.meta?.icon),
              permission: this.getPermission(child.name),
              path: this.generateMobilePath(child),
              component: child.component,
              meta: child.meta
            }
            
            module.children.push(mobileRoute)
          })
        }
        
        // 只添加有子路由的模块
        if (module.children.length > 0) {
          mobileModules.push(module)
        }
      })
      
      return mobileModules
    },
    
    // 获取移动端图标
    getMobileIcon(backendIcon) {
        if (!backendIcon || backendIcon === '#') {
          return 'gear-filled'
        }
        
        const iconMapping = {
          'tree': 'tree-filled', 'peoples': 'staff-filled', 'user': 'person-filled', 'system': 'settings-filled',
          'tree-table': 'color', 'dict': 'bars', 'edit': 'gear-filled', 'message': 'chat-filled',
          'log': 'wallet-filled', 'code': 'code-filled', 'monitor': 'eye-filled', 'online': 'person-filled',
          'job': 'work-filled', 'druid': 'chart-filled', 'server': 'gear-filled', 'redis': 'database-filled',
          'list': 'list-filled', 'money': 'wallet-filled', 'chart': 'chart-filled', 'textarea': 'document-filled',
          'build': 'gear-filled', 'table': 'table-filled', 'excel': 'file-filled', 'nested': 'tree-filled',
          'tab': 'list-filled', 'people': 'person-filled', 'zip': 'folder-filled', 'swagger': 'link-filled',
          'tool': 'tool-filled', 'lock': 'lock-filled', 'switch': 'refresh-filled', 'time-range': 'clock-filled',
          'bug': 'close-filled', 'checkbox': 'checkmark-filled', 'example': 'document-filled', 'form': 'list-filled',
          'guide': 'help-filled', 'add': 'plus-filled', 'date': 'calendar-filled', 'date-range': 'calendar-filled',
          'dashboard': 'chart-filled', 'barcode': 'scan-filled', 'component': 'gear-filled', 'fault': 'close-filled',
          'input': 'edit-filled', 'shopping': 'cart-filled', 'wechat': 'chat-filled', 'link': 'link-filled',
          'logininfor': 'person-filled', 'drag': 'drag-filled', 'icon': 'star-filled', 'documentation': 'document-filled',
          'cascader': 'list-filled', 'folder': 'folder-filled', 'file': 'file-filled', 'scan': 'scan-filled',
          'star': 'star-filled', 'help': 'help-filled', 'cart': 'cart-filled', 'chat': 'chat-filled',
          'work': 'work-filled', 'database': 'database-filled', 'gear': 'gear-filled', 'wallet': 'wallet-filled',
          'document': 'document-filled', 'clock': 'clock-filled', 'close': 'close-filled', 'checkmark': 'checkmark-filled',
          'plus': 'plus-filled', 'calendar': 'calendar-filled', 'refresh': 'refresh-filled',
          'clientname': 'person-filled', 'alignBottom': 'list-filled', 'inbound': 'box-filled',
		  'snTaking' :'file-filled'
        }
        
        return iconMapping[backendIcon] || 'gear-filled'
    },
    
    // 获取权限标识
    getPermission(routeName) {
        const permissionMapping = {
          'User': 'system:user:list', 'Dept': 'system:dept:list', 'Role': 'system:role:list', 'Menu': 'system:menu:list',
          'Dict': 'system:dict:list', 'Config': 'system:config:list', 'Notice': 'system:notice:list', 'Log': 'system:log:list',
          'Monitor': 'monitor:list', 'Online': 'monitor:online:list', 'Job': 'monitor:job:list', 'Server': 'monitor:server:list',
          'Sales': 'sales:list', 'SaleOrder': 'sales:order:list', 'SaleReturn': 'sales:return:list', 'Finance': 'finance:list',
          'Financial': 'finance:financial:list', 'Mes/md': 'mes:md:list', 'Main': 'mes:bom:list', 'Mditem': 'mes:item:list',
          'Client': 'mes:client:list', 'Vendor': 'mes:vendor:list', 'Mes/wm': 'mes:wm:list', 'Warehouse': 'mes:warehouse:list',
          'Wmstock': 'mes:stock:list', 'Itemrecpt': 'mes:itemrecpt:list', 'Issue': 'mes:issue:list', 'Productrecpt': 'mes:productrecpt:list',
          'Productsales': 'mes:productsales:list', 'Mes/dv': 'mes:dv:list', 'Machinery': 'mes:machinery:list', 'Checkrecord': 'mes:checkrecord:list',
          'Repair': 'mes:repair:list', 'Mes/pro': 'mes:pro:list', 'Workorder': 'mes:workorder:list', 'Process': 'mes:process:list',
          'Feedback': 'mes:feedback:list', 'Mes/qc': 'mes:qc:list', 'Qcdefect': 'mes:qcdefect:list', 'Iqc': 'mes:iqc:list',
          'Ipqc': 'mes:ipqc:list', 'Oqc': 'mes:oqc:list', 'Report': 'mes:report:list', 'Chart': 'mes:chart:list',
          'Inbound': 'app:inbound',  // 入库权限
          'Outbound': 'app:outbound', // 出库权限
		  'snTaking' :'app:snTaking'
        }
        
        return permissionMapping[routeName] || null
    },
    
    // 生成移动端路径
    generateMobilePath(route) {
      if (route.component) {
        const componentPath = route.component.replace(/^\//, '')
        
        // 处理 app/inbound 这样的路径
        if (componentPath.includes('/')) {
          return `/pages/${componentPath}/index`
        }
        
        if (componentPath.startsWith('pages/')) {
          return `/${componentPath}`
        } else {
          return `/pages/${componentPath}/index`
        }
      }
      
      const routeName = route.name?.toLowerCase() || 'unknown'
      return `/pages/${routeName}/index`
    },
    
    // 获取默认模块
    getDefaultModules() {
        const modules = [
          {
            name: '基础功能',
            icon: 'gear-filled',
            children: [
              {
                path: '/pages/mine/info/index',
                name: '个人信息',
                title: '个人信息',
                icon: 'person-filled',
                permission: null
              },
              {
                path: '/pages/mine/setting/index',
                name: '应用设置',
                title: '应用设置',
                icon: 'settings-filled',
                permission: null
              },
              {
                path: '/pages/mine/help/index',
                name: '帮助中心',
                title: '帮助中心',
                icon: 'help-filled',
                permission: null
              },
              {
                path: '/pages/mine/about/index',
                name: '关于我们',
                title: '关于我们',
                icon: 'info-filled',
                permission: null
              }
            ]
          }
        ]
        
        // 动态添加app模块，根据权限过滤
        const appChildren = []
        
        // 检查入库权限
        // if (this.hasMESPermission('app:inbound')) {
        //   appChildren.push({
        //     path: '/pages/app/inbound/index',
        //     name: '入库',
        //     title: '入库管理',
        //     icon: 'download-filled',
        //     permission: 'app:inbound'
        //   })
        // }
        
        // // 检查出库权限
        // if (this.hasMESPermission('app:outbound')) {
        //   appChildren.push({
        //     path: '/pages/app/outbound/index',
        //     name: '出库',
        //     title: '出库管理',
        //     icon: 'shop-filled',
        //     permission: 'app:outbound'
        //   })
        // }
        
        // 只有当有app功能时才添加app模块
        if (appChildren.length > 0) {
          modules.push({
            name: 'app',
            icon: 'gear-filled',
            children: appChildren
          })
        }
        
        return modules
    },
    
    // 检查MES权限
    hasMESPermission(permission) {
      if (this.isDev) {
        console.log(`=== 检查权限: ${permission} ===`)
        console.log('用户权限列表:', this.permissions)
      }
      
      if (!this.permissions || this.permissions.length === 0) {
        if (this.isDev) console.log('用户无权限数据')
        return false
      }
      
      // 检查是否有超级管理员权限
      if (this.permissions.includes('*:*:*')) {
        if (this.isDev) console.log('用户拥有超级管理员权限，允许访问所有模块')
        return true
      }
      
      // 检查具体权限
      const hasPermission = this.permissions.includes(permission)
      if (this.isDev) console.log(`权限检查结果: ${hasPermission}`)
      return hasPermission
    },
    
    // 点击轮播图
    clickBannerItem(item) {
      console.info('点击轮播图:', item)
    },
    
    // 轮播图切换
    changeSwiper(e) {
      this.current = e.detail.current
    },
    
    // 宫格点击事件
    changeGrid(e) {
      if (this.isDev) {
        console.log('=== uni-grid 点击事件触发 ===')
        console.log('宫格点击:', e)
      }
      
      // 由于 uni-grid 的索引计算比较复杂，我们暂时禁用这个事件
      // 让直接的点击事件来处理跳转
      if (this.isDev) console.log('uni-grid 事件被忽略，使用直接点击事件')
    },
    
    // 导航到模块
    navigateToModule(module) {
      if (this.isDev) {
        console.log('=== 点击模块事件触发 ===')
        console.log('点击模块:', module)
      }
      
      if (!module.path) {
        console.error('模块路径未配置:', module)
        uni.showToast({
          title: '模块路径未配置',
          icon: 'none'
        })
        return
      }
      // 简化权限检查 - 对于admin用户直接允许访问
      if (module.permission && !this.hasMESPermission(module.permission)) {
        console.log('无权限访问该模块:', module.permission)
        console.log('用户权限:', this.permissions)
        uni.showToast({
          title: '无权限访问该模块',
          icon: 'none'
        })
        return
      }
      
      // 构建跳转URL
      let url = module.path
      if (module.params && Object.keys(module.params).length > 0) {
        const params = new URLSearchParams(module.params).toString()
        url += `?${params}`
      }
      
      if (this.isDev) {
        console.log('准备跳转到:', url)
        console.log('模块完整信息:', JSON.stringify(module, null, 2))
      }
      
      // 验证路径格式
      if (!url.startsWith('/pages/')) {
        console.error('路径格式错误，必须以 /pages/ 开头:', url)
        uni.showToast({
          title: '路径格式错误',
          icon: 'none'
        })
        return
      }
      
      // 直接跳转，不进行页面存在检查
      if (this.isDev) console.log('开始跳转...')
      
      // 先显示一个提示，确认点击事件被处理
      uni.showToast({
        title: `正在跳转到: ${module.name}`,
        icon: 'loading',
        duration: 1000
      })
      
      // 延迟跳转，确保提示显示
      setTimeout(() => {
        if (this.isDev) {
          console.log('执行跳转:', url)
          console.log('直接跳转到入库页面:', url)
        }
        uni.navigateTo({
          url: url,
          success: () => {
            if (this.isDev) {
              console.log('=== 入库页面跳转成功 ===')
              console.log('跳转到:', url)
            }
          },
          fail: (err) => {
            console.error('=== 入库页面跳转失败 ===')
            console.error('跳转失败:', err)
            console.error('目标URL:', url)
            
            // 尝试使用 reLaunch
            if (this.isDev) console.log('尝试使用 reLaunch 跳转...')
            uni.reLaunch({
              url: url,
              success: () => {
                if (this.isDev) console.log('=== reLaunch 跳转成功 ===')
              },
              fail: (reLaunchErr) => {
                console.error('=== reLaunch 也失败了 ===')
                console.error('reLaunch 失败:', reLaunchErr)
                uni.showToast({
                  title: '页面跳转失败: ' + (err.errMsg || '未知错误'),
                  icon: 'none'
                })
              }
            })
          }
        })
      }, 100)
    },
    
    // 检查页面是否存在
    isPageExists(path) {
      // 定义已存在的页面列表
      const existingPages = [
        '/pages/mine/info/index',
        '/pages/mine/setting/index',
        '/pages/mine/help/index',
        '/pages/mine/about/index',
        '/pages/common/webview/index',
        '/pages/common/textview/index',
        '/pages/app/inbound/index',  // 添加入库页面
        '/pages/app/outbound/index'  // 添加出库页面
      ]
      
      return existingPages.includes(path)
    }
  }
}
</script>

<style lang="scss" scoped>
/* #ifndef APP-NVUE */
page {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #fff;
  min-height: 100%;
  height: auto;
}

view {
  font-size: 14px;
  line-height: inherit;
}
/* #endif */

.work-container {
  width: 100%;
  padding: 0 20rpx;
  box-sizing: border-box;
  
  .uni-swiper-dot-box {
    width: 100%;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .swiper-box {
    width: 100%;
    height: 300rpx;
    border-radius: 16rpx;
    overflow: hidden;
  }
  
  .swiper-item {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    
    .banner-image {
      width: 100%;
      height: 100%;
      border-radius: 16rpx;
    }
  }
  
  .module-section {
    margin-bottom: 40rpx;
    width: 100%;
    
    .grid-body {
      width: 100%;
      padding: 20rpx 0;
    }
  }
  
  .text {
    text-align: center;
    font-size: 26rpx;
    margin-top: 12rpx;
    color: #333;
    word-break: break-all;
    line-height: 1.4;
  }

  .grid-item-box {
    flex: 1;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30rpx 20rpx;
    cursor: pointer;
    transition: all 0.3s;
    min-height: 140rpx;
    box-sizing: border-box;
    
    &:active {
      background-color: #f5f5f5;
      transform: scale(0.95);
    }
  }

  .no-permission {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 40rpx;
    
    .no-permission-text {
      margin-top: 20rpx;
      color: #999;
      font-size: 28rpx;
      text-align: center;
    }
  }

  // 手机端样式（默认）
  @media screen and (max-width: 600px) {
    .swiper-box {
      height: 280rpx;
    }
    
    .text {
      font-size: 24rpx;
    }
    
    .grid-item-box {
      padding: 25rpx 15rpx;
      min-height: 120rpx;
    }
  }

}

// 平板端样式
@media screen and (min-width: 600px) and (max-width: 900px) {
  .work-container {
    padding: 0 40rpx;
    
    .swiper-box {
      height: 350rpx;
    }
    
    .text {
      font-size: 28rpx;
    }
    
    .grid-item-box {
      padding: 40rpx 25rpx;
      min-height: 160rpx;
    }
  }
}

// 大屏iPad样式
@media screen and (min-width: 900px) {
  .work-container {
    padding: 0 60rpx;
    max-width: 1200px;
    margin: 0 auto;
    
    .swiper-box {
      height: 400rpx;
    }
    
    .text {
      font-size: 30rpx;
    }
    
    .grid-item-box {
      padding: 50rpx 30rpx;
      min-height: 180rpx;
    }
    
    .module-section {
      margin-bottom: 60rpx;
    }
  }
}
</style>